import datetime
import logging
import traceback
import json
import pymysql

from core.config import Config



class Order(object):
    def __init__(self):
        self.order_num_1 = 0
        self.order_num_2 = 0

    @classmethod
    def get_order_num(cls, shop_id):
        order_num_obj = Order()

        # 获取未来一小时内的订单数
        order_num_obj.order_num_1 = cls.get_0_1_hour_order_num(shop_id)

        # 获取未来1到2小时内的订单数
        order_num_obj.order_num_2 = cls.get_1_2_hour_order_num(shop_id)

        return order_num_obj

    """
        0-1小时内的待配送订单数
    """
    @classmethod
    def get_0_1_hour_order_num(cls, shop_id):
        start = datetime.datetime.now()
        end = start + datetime.timedelta(hours=1)
        return cls.get_order_num_common(shop_id, start, end)

    """
        1-2小时内的待配送订单数
    """
    @classmethod
    def get_1_2_hour_order_num(cls, shop_id):
        now = datetime.datetime.now()
        start = now + datetime.timedelta(hours=1)
        end = now + datetime.timedelta(hours=2)
        return cls.get_order_num_common(shop_id, start, end)

    @classmethod
    def get_order_num_common(cls, shop_id, start, end):
        # 订单列表
        order_num = 0

        # 连接数据库
        db = pymysql.connect(**Config.ofs_delivery_center)

        try:
            cursor = db.cursor()

            sql = """SELECT
                        count(order_id) as order_num
                    FROM ofs_delivery_center.t_delivery_order
                    WHERE 1 = 1
                    AND shop_id = %s
                    AND status < 80
                    AND workforce_type = 0
                    AND end_flag = 0
                    AND earliest_delivery_time > %s
                    AND earliest_delivery_time <= %s
                    """

        # db = pymysql.connect(**Config.ofs_logistics_center)
        #
        # try:
        #     cursor = db.cursor()
        #
        #     sql = """SELECT
        #                 count(order_id) as order_num
        #             FROM ofs_logistics_center.t_delivery_task
        #             WHERE 1 = 1
        #             AND delivery_node_id = %s
        #             AND order_type = 'toc_sales'
        #             AND delivery_status IN ('wait_release','wait_dispatch','wait_pickup','wait_deliver')
        #             AND end_flag = 0
        #             AND carrier_company_code = 'yh_delivery'
        #             AND carrier_type = 'rider'
        #             AND deliver_earliest_time > %s
        #             AND deliver_latest_time <= %s
        #             """

            cursor.execute(sql, (shop_id, start, end))
            results = cursor.fetchall()

            # 解析数据
            for row in results:
                order_num = int(row["order_num"])

            return order_num

        except Exception as e:
            traceback.print_exc()
            logging.error(f"获取订单数异常{e}")
        finally:
            db.close()